package com.siqi.hr.system.custom.dao.mysql;

import com.siqi.hr.system.custom.dao.intf.QueryDao;
import com.siqi.hr.system.custom.entity.Query;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 查询条件dao实现类层
 * @author     xiaogq
 * Created by xiaogoingqin on 2016/7/24.
 */
@Repository("queryDao")
public class QueryDaoImpl implements QueryDao {

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<Query> queryListShowCustQueryList(String employeeId, Integer entityId) {
        StringBuffer sql = new StringBuffer(" select q.id,q.name,q.extparam from sys_custom_query q where q.list_show = true and (  (q.is_system = true  and 1 <> "+entityId);
        sql.append(" and exists ( select 0 from sys_custom_entity where table_code = " + entityId + " and set_element = false )  ");
        sql.append(" and q.id not in (select query_id from sys_custom_query_setting where emp_id =  '"+ employeeId+"' and entity_id = "+entityId+")) ");
        sql.append(" || ( q.is_system = false and q.entity_id = "+entityId+" and q.emp_id = '"+employeeId+"' )) order by q.position");
        try {
            return this.jdbcTemplate.query(sql.toString(), new Query.MainField());
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        return new ArrayList<Query>();
    }

    @Override
    public void removeFieldFromCondition(Integer tableCode, String fieldName) {
        String sql = " SELECT id,entity_id,extparam FROM `sys_custom_query`  where IFNULL(extparam,'') <> '' and ( entity_id = "+ tableCode+ " or extparam like '%pk\\_t\\_" + tableCode + "\\_%') ";
        List<Map<String,Object>> queryList = this.jdbcTemplate.queryForList(sql);

        String regEx = "pk_t_" + tableCode + "_\\d" + "___" + fieldName;
        Pattern pattern = Pattern.compile(regEx, 2);

        if (queryList != null && queryList.size() > 0) {
            List<String> condSql = new ArrayList<String>();
            for (Map<String,Object> map : queryList) {
                Integer queryEntId = Integer.valueOf(Integer.parseInt(map.get("entity_id").toString()));
                String cond = map.get("extparam").toString().replaceAll(",\\{", ";\\{");
                String[] consArr = cond.split(";");
                boolean existBoo = false;
                for (String sc : consArr) {
                    if (((queryEntId == tableCode) && (sc.indexOf(fieldName) > 0)) || ((queryEntId != tableCode) && (pattern.matcher(sc).find()))) {
                        existBoo = true;
                        consArr = (String[]) ArrayUtils.removeElement(consArr,sc);
                    }
                }

                if (existBoo) {
                    String updsql = "update sys_custom_query set extparam = '" + (consArr.length == 0 ? "" : StringUtils.join(consArr, ",").replaceAll("'", "\\\\'"))+ "' " + " where id = " + map.get("id");
                    condSql.add(updsql);
                }
            }

            if (condSql.size() > 0)
                this.jdbcTemplate.batchUpdate(condSql.toArray(new String[condSql.size()]));
        }
    }

}
